from django.shortcuts import render,redirect
# 导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
# 导入类视图
from django.views import View


import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入加密库
import hashlib
# 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io

import requests

# 导入上传文件夹配置
from django_test.settings import UPLOAD_ROOT
import os

# 导入原生sql模块
from django.db import connection

import jwt

# 导入redis数据库
import redis

# 导入时间模块
import time

# 导入公共目录变量
from django_test.settings import BASE_DIR

# 导包
from django.db.models import Q,F

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

# 导入表
from myapp.models import User
# 导入序列化对象
from myapp.myser import UserSer

# 导包
import redis

# 图像处理
import cv2

# 定义地址和端口
host = '127.0.0.1'
port = 6379

# 建立redis连接
r = redis.Redis(host=host,port=port)

# 导入pymongo
import pymongo

# 建立mongo的链接对象
mongo_client = pymongo.MongoClient(host='localhost', port=27017)

# 又拍云上传
import upyun
# 删除文件
class UpDel(APIView):
    def get(self,request):
        # 获取文件
        file = request.FILES.get('file')

        # 新建又拍云实例    空间名称       操作员                 密码
        up = upyun.UpYun('tianshangxing', 'xing', 'tTj32mkTmBeMoM9pUYo9AG5tuNx5f7fF')

		# 声明头部信息
        headers = {'x-gmkerl-rotate': 'auto'}

        up.delete('/kaosi/' + file.name)

        return Response({'message': '删除成功'})

# 定义文件上传类
class UploadUp(APIView):
	def post(self,request):
		# 获取文件
		file = request.FILES.get('file')
		# 新建又拍云实例    空间名称       操作员                 密码
		up = upyun.UpYun('tianshangxing', 'xing', 'tTj32mkTmBeMoM9pUYo9AG5tuNx5f7fF')
		# 声明头部信息
		headers = {'x-gmkerl-rotate': 'auto'}

		# 上传图片
		for chunk in file.chunks():
			# 又拍云路径
			res = up.put('jwt.png', chunk, checksum=True, headers=headers)

		return Response({'filename': file.name})

# 文件上传
class UploadFile(APIView):
	# get 超出文件限制报错
    def post(self, request):
        # 接收参数
        myfile = request.FILES.get('file')

        # 建立文件流对象 定义写文件路径
        f = open(os.path.join(UPLOAD_ROOT, '', myfile.name.replace('"', '')), 'wb')

        # 写入
        for chunk in myfile.chunks():
            f.write(chunk)
        f.close()

        # 打开图片
        im = Image.open(myfile)

        # 生成画笔对象
        draw = ImageDraw.Draw(im)

        # 设置字体
        my_font = ImageFont.truetype('c:\\Windows\\Fonts\\BAUHS93.TTF', size=50)

        # 修改图片
        draw.text((1350, 800), 'django2.0.4', font=my_font ,fill=(76, 234, 124, 180))

        # 定义存储路径
        storagepath='./static/upload/'+myfile.name

        # 读图
        im = cv2.imread(storagepath)

        # 压缩jpg
        cv2.imwrite(storagepath, im, [cv2.IMWRITE_JPEG_QUALITY, 50])
            
        im.save(storagepath)

        return Response({'filename': myfile.name.replace('"', '')})



# 登录接口
class Login(APIView):
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', None)
        password = request.GET.get('password', None)

        # 查询数据
        user = User.objects.filter(username=username, password=make_password(password)).first()

        if user:
            return Response({'code': 200, 'message': '登陆成功'})
        
        else:
            return Response({'code': 403, 'message': '用户名或密码错误'})

# MD5加密
def make_password(mypass):
    # 生成MD5对象
    md5 = hashlib.md5()
    # 转码操作
    mypass_utf8 = str(mypass).encode(encoding='utf-8')
    # 加密操作
    md5.update(mypass_utf8)
    # 返回密文
    return md5.hexdigest()

# 注册接口
class Register(APIView):
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', None)
        password = request.GET.get('password', None)

        # 查询数据
        user = User.objects.filter(username=username).first()

        # 排重
        if user:
            return Response({'code': 403, 'message': '该用户名已存在'})

        # 入库
        user = User(username=username, password=make_password(password)).save()

        return Response({'code': 200, 'message': '注册成功'})


